<script setup lang="ts">
import { ref } from 'vue'

const number = ref(0)

function debounce(fn: (...args: any[]) => void, time: number) {
  let timer: NodeJS.Timeout
  return () => {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => fn(), time)
  }
}

function handleMouseMove() {
  number.value += 1
  console.log('number = ' + number.value)
}

// 创建一个防抖函数
const debouncedHandleMouseMove = debounce(handleMouseMove, 500)
</script>

<template>
  <div class="debounce-demo__container">
    <h3>Debounce 防抖演示</h3>
    <div class="box" @mousemove="debouncedHandleMouseMove">
      <p>{{ number }}</p>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.box {
  width: 500px;
  height: 500px;
  box-sizing: border-box;
  margin: 0 auto;
  background-color: rgb(9, 122, 160);

  p {
    text-align: center;
    font-size: 2rem;
    padding: 10px;
    color: #fff;
  }
}
</style>
